# coding: utf8

from django.views.generic import TemplateView, View, ListView
from django.shortcuts import render, redirect, get_object_or_404
from django.contrib.auth.models import User
from django.http import JsonResponse, Http404
from django.core.paginator import Paginator, EmptyPage
from dashboard.models import Department
from django.conf import settings
from django.utils.decorators import method_decorator
from django.contrib.auth.decorators import permission_required,login_required

class UserListView(TemplateView):
    template_name = 'user/userlist.html'
    before_index = 3
    after_index = 2

    def get(self, request, *args, **kwargs):
        self.request = request
        return super(UserListView, self).get(request, *args, **kwargs)

    def get_context_data(self, **kwargs):
        context = super(UserListView, self).get_context_data(**kwargs)
        userlist = User.objects.all()  #<class 'django.db.models.query.QuerySet'>
        # context['userlist'] = userlist
        page_of_record_num = 5
        paginator = Paginator(userlist, page_of_record_num)
        cur_page_num = int(self.request.GET.get('page', 1))
        page_obj = paginator.page(cur_page_num)
        context['page_obj'] = page_obj
        start = cur_page_num - self.before_index
        end = cur_page_num + self.after_index
        if start < 0:
            start = 0
            end = start + self.before_index + self.after_index
        elif end > paginator.num_pages:
            end = paginator.num_pages
            start = end - self.before_index - self.after_index
        context['page_range'] = page_obj.paginator.page_range[start:end]
        return context

class ModifyUserStatusView(View):
    def post(self, request, *args, **kwargs):
        ret = { "status": 0}
        user_id = request.POST.get("user_id", None)
        try:
            user = User.objects.get(pk=user_id)
            if user.is_active:
                user.is_active = False
            else:
                user.is_active = True
            user.save()
        except User.DoesNotExist:
            ret['status'] = 1
            ret['errmsg'] = "用户不存在"
        return JsonResponse(ret, safe=True)

class UserLISTVIEW(ListView):
    model = User
    template_name = 'user/userlistl.html'
    paginate_by = 5
    context_object_name = 'userlist'
    before_index = 3
    after_index = 2

    def get_context_data(self, **kwargs):
        context = super(UserLISTVIEW, self).get_context_data(**kwargs)
        context['page_range'] = self.get_page_range(context['page_obj'])
        return context

    def get_page_range(self, page_obj):
        cur_page_num = page_obj.number
        start = cur_page_num - self.before_index
        end = cur_page_num + self.after_index
        if start < 0:
            start = 0
            end = start + self.before_index + self.after_index
        elif end > page_obj.paginator.num_pages:
            end = page_obj.paginator.num_pages
            start = end - self.before_index - self.after_index
        return page_obj.paginator.page_range[start:end]

class ModifyDepartmentView(TemplateView):
    template_name = 'user/modify_department.html'

    def get_context_data(self, **kwargs):
        context = super(ModifyDepartmentView, self).get_context_data(**kwargs)
        context['departments'] = Department.objects.all()
        user_id = self.request.GET.get('user', None)
        context['user_obj'] = get_object_or_404(User, pk=user_id)
        return context

    @method_decorator(login_required)
    @method_decorator(permission_required("dashboard.change_department", login_url=settings.PERMISSION_NONE_URL))
    def get(self, request, *args, **kwargs):
        self.request = request
        return super(ModifyDepartmentView, self).get(request, *args, **kwargs)

    @method_decorator(login_required)
    @method_decorator(permission_required("dashboard.change_department", login_url=settings.PERMISSION_NONE_URL))
    def post(self, request, *args, **kwargs):
        user_id = request.POST.get('id', None)
        department_id = request.POST.get('department', None)
        if not user_id or not department_id:
            raise Http404
        try:
            user_obj = User.objects.get(pk=user_id)
            department_obj = Department.objects.get(pk=department_id)
        except:
            raise Http404
        else:
            user_obj.profile.department = department_obj
            user_obj.profile.save()
        return redirect("/user/userlist/")

class ModifyUserPhoneView(TemplateView):
    template_name = "user/modify_phone.html"

    def get_context_data(self, **kwargs):
        context = super(ModifyUserPhoneView, self).get_context_data(**kwargs)
        uid = self.request.GET.get('uid', None)
        context['user_obj'] = get_object_or_404(User, pk=uid)
        return context

    def post(self, request, *args, **kwargs):
        uid = request.POST.get('id', None)
        phone = request.POST.get('phone', None)
        user_obj = get_object_or_404(User, pk=uid)
        user_obj.profile.phone = phone
        user_obj.profile.save()
        return render(request, settings.TEMPLATE_JUMP, {"status": 0, "next_url": "/user/userlist/"})